package jmine.tec.rpc.common.lazy;

import java.io.Serializable;

import jmine.tec.rpc.common.entity.EntityRest;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * Inicializador de representações lazy.
 * 
 * @author lundberg
 */
public class LazyRepresentationInitializer {

    private final EntityRest<?> service;

    private final Serializable representationId;

    private transient Object representation;

    /**
     * Construtor
     * 
     * @param service service
     * @param representationId representationId
     */
    public LazyRepresentationInitializer(EntityRest<?> service, Serializable representationId) {
        this.service = service;
        this.representationId = representationId;
    }

    /**
     * Obtém uma referência para a representação, buscando se necessário
     * 
     * @return representation
     * @throws BeanNotFoundException BeanNotFoundException
     */
    public Object getRepresentation() throws BeanNotFoundException {
        if (this.representation == null) {
            this.representation = this.fetchRepresentation();
        }
        return this.representation;
    }

    /**
     * Busca a representação, caso já não tenha sido buscada.
     * 
     * @return representation
     * @throws BeanNotFoundException BeanNotFoundException
     */
    private synchronized Object fetchRepresentation() throws BeanNotFoundException {
        if (this.representation != null) {
            return this.representation;
        } else {
            return this.service.findByIdentification(this.representationId);
        }
    }

    /**
     * Obtém a classe da representação
     * 
     * @return EntityRestService
     */
    public Class<?> getRepresentationClass() {
        return this.service.getRepresentationClass();
    }

    /**
     * Obtém o ID da representação
     * 
     * @return Serializable
     */
    public Serializable getRepresentationId() {
        return this.representationId;
    }

}
